#!/bin/bash

# Run script for image2pcd project
# This script will run the image2pcd executable with proper error handling

set -e # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Project root directory (parent of scripts directory)
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EXECUTABLE="$PROJECT_DIR/image2pcd"

echo -e "${BLUE}=== Running image2pcd ===${NC}"

# Check if executable exists
if [ ! -f "$EXECUTABLE" ]; then
    echo -e "${RED}Error: Executable not found at $EXECUTABLE${NC}"
    echo -e "${YELLOW}Please run ./build.sh first to build the project${NC}"
    exit 1
fi

# Check if executable is executable
if [ ! -x "$EXECUTABLE" ]; then
    echo -e "${YELLOW}Making executable runnable...${NC}"
    chmod +x "$EXECUTABLE"
fi

# Change to project directory to ensure relative paths work correctly
cd "$PROJECT_DIR"

echo -e "${GREEN}Starting image2pcd application...${NC}"
echo -e "${YELLOW}Note: This application may require GUI display. If running over SSH, ensure X11 forwarding is enabled.${NC}"
echo -e "${YELLOW}Press Ctrl+C to stop the application.${NC}"
echo ""

# Run the executable and capture its exit code
"$EXECUTABLE" "$@"
EXIT_CODE=$?

echo ""
if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}Application completed successfully${NC}"
else
    echo -e "${RED}Application exited with code: $EXIT_CODE${NC}"
fi

echo -e "${BLUE}=== Run Complete ===${NC}"
exit $EXIT_CODE
